package com.markerhub.controller;

import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysOperationLog;
import com.markerhub.service.SysOperationLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 操作日志Controller
 */
@Api(tags = "操作日志管理")
@RestController
@RequestMapping("/api/sys-operation-log")
public class SysOperationLogController extends BaseController {

    @Autowired
    private SysOperationLogService sysOperationLogService;

    /**
     * 获取操作日志列表
     */
    @PreAuthorize("hasAuthority('sys:operation-log:list')")
    @ApiOperation(value = "获取操作日志列表", notes = "获取所有操作日志信息，支持分页查询")
    @GetMapping("/list")
    public Result list(@RequestParam(required = false) String username, @RequestParam(required = false) String operation) {
        // 使用BaseController中的getPage()方法获取分页参数
        Page<SysOperationLog> page = getPage();
        // 构建查询条件
        QueryWrapper<SysOperationLog> wrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            wrapper.like("username", username);
        }
        if (operation != null && !operation.isEmpty()) {
            wrapper.like("operation", operation);
        }
        // 按创建时间倒序排序
        wrapper.orderByDesc("created");
        // 执行分页查询
        Page<SysOperationLog> pageData = sysOperationLogService.page(page, wrapper);
        return Result.succ(200, "获取系统操作日志列表成功", pageData);
    }

    /**
     * 查询操作日志 - 分页
     */
    @PreAuthorize("hasAuthority('sys:operation-log:list')")
    @ApiOperation(value = "查询操作日志", notes = "根据条件查询操作日志")
    @GetMapping("/query")
    public Result query() {
        // 使用BaseController中的getPage()方法获取分页参数
        Page<SysOperationLog> page = getPage();
        // 执行分页查询
        Page<SysOperationLog> pageData = sysOperationLogService.page(page);
        return Result.succ(200, "查询系统操作日志成功", pageData);
    }

    /**
     * 根据ID获取系统操作日志信息
     */
    @PreAuthorize("hasAuthority('sys:operation-log:list')")
    @ApiOperation(value = "获取操作日志详情", notes = "根据ID获取系统操作日志详细信息")
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable Long id) {
        SysOperationLog log = sysOperationLogService.getById(id);
        return Result.succ(200, "获取系统操作日志信息成功", log);
    }

    /**
     * 删除系统操作日志（单个）
     */
    @PreAuthorize("hasAuthority('sys:operation-log:delete')")
    @ApiOperation(value = "删除操作日志", notes = "根据ID删除单个系统操作日志")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean deleted = sysOperationLogService.removeById(id);
        return deleted ? Result.succ(200, "删除系统操作日志成功", null) : Result.fail("删除系统操作日志失败");
    }
    
    /**
     * 清空操作日志
     */
    @PreAuthorize("hasAuthority('sys:operation-log:clean')")
    @ApiOperation(value = "清空操作日志", notes = "清空所有系统操作日志")
    @DeleteMapping("/clean")
    public Result clean() {
        // 使用QueryWrapper条件来避免MyBatis-Plus的全表删除限制
        QueryWrapper<SysOperationLog> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("id"); // 添加一个永远为真的条件
        boolean cleaned = sysOperationLogService.remove(wrapper);
        return cleaned ? Result.succ(200, "清空操作日志成功", null) : Result.fail("清空操作日志失败");
    }
    
    /**
     * 分析操作日志
     */
    @PreAuthorize("hasAuthority('sys:operation-log:analysis')")
    @ApiOperation(value = "分析操作日志", notes = "对操作日志进行分析统计")
    @GetMapping("/analysis")
    public Result analysis(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String type) {
        Date startDate = null;
        Date endDate = null;
        
        try {
            // 处理时间参数，支持ISO格式时间(含时区信息Z)
            if (startTime != null && !startTime.isEmpty()) {
                // 使用ZonedDateTime解析带时区的ISO时间字符串
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(startTime);
                startDate = Date.from(zonedDateTime.toInstant());
            }
            
            if (endTime != null && !endTime.isEmpty()) {
                // 使用ZonedDateTime解析带时区的ISO时间字符串
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(endTime);
                endDate = Date.from(zonedDateTime.toInstant());
            }
            
            // 调用服务层方法进行分析
            Map<String, Object> result = sysOperationLogService.analysis(startDate, endDate, type);
            
            return Result.succ(200, "操作日志分析成功", result);
        } catch (Exception e) {
            // 捕获并记录异常，返回具体错误信息
            e.printStackTrace();
            return Result.fail("时间格式解析错误：" + e.getMessage());
        }
    }
}